﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web.Mvc;
using System.Web.Routing;
using ShopB2C.Entity;
using ShopB2C.Enums;
using ShopB2C.Helper;
using ShopB2C.Interfaces;
using ShopB2C.Parameters;
using ShopB2C.ViewModels;

namespace ShopB2C.Controllers.Brower {
    public partial class ConsultController : BaseController {
        private const string _moduleKey = "Product";
        private static IProductPreview _productPreView;
        private static IClassify _classify;
        private static IConsult _consult;
        private static string _userFaceRoot;

        public ConsultController() {
            _productPreView = DataBaseExecuter.CreateClassByName<IProductPreview>("ProductPreView");
            _classify = DataBaseExecuter.CreateClassByName<IClassify>("ClassIfy");
            _consult = DataBaseExecuter.CreateClassByName<IConsult>("Consult");
            _userFaceRoot = ConfigHelper.GetValue(ConfigNodeNames.System, "UserFaceRoot");
        }

        protected override void Initialize(RequestContext requestContext) {
            base.Initialize(requestContext);
            this.SiteMapPathAdd("首页", Url.Action("Index", "Home"));
            this.SiteMapPathAdd("所有商品", Url.Action("ProductList", "Product", new {
                productParams = new ProductParam().ToString()
            }));
            ViewData["ImageRoot"] = _imageRoot;
        }

        // 购买咨询
        public ActionResult ConsultList(int productId = 0, int consultId = 0, int pageIndex = 1) {
            ProductEntity productView = _productPreView.ProductView(productId, _user.Uid);
            if (productView == null) {
                return Content("没有找到相关商品信息!");
            }
            // 购买咨询
            ConsultParameters cpa = new ConsultParameters() {
                ProductId = productId,
                PageIndex = pageIndex,
                PageSize = 10,
                Uid = this._user.Uid
            };
            List<ConsultEntity> consultList = _consult.GetConsultList(cpa);
            ConsultEntity ce = this._user.Uid > 0 && consultId > 0
                ? _consult.GetConsultById(consultId)
                : new ConsultEntity();
            ce.Uid = this._user.Uid;
            ce.Content = Htmls.DecodeHtml(ce.Content);
            // sitemappath
            this.AddSiteMapPath(productView);
            this.SiteMapPathAdd(productView.SubName,
                Url.Action("PreView", "Product", new { ProductId = productId }));
            this.SiteMapPathAdd("商品购买咨询");
            // 分页
            object pager = this.CreatePager(Url.Action("ConsultList", "Consult", new {
                productId = productId,
                pageIndex = "{0}"
            }), cpa.PageCount, pageIndex);

            return View(new ConsultViewModel() {
                ImageRoot = _imageRoot,
                UserFaceRoot = _userFaceRoot,
                Product = productView,
                Consult = ce,
                ConsultList = consultList ?? new List<ConsultEntity>(),
                RowsCount = cpa.RowsCount,
                Pager = pager
            });
        }
        // 删除
        public ActionResult ConsultDelete(int productId = 0, int consultId = 0) {
            _consult.ConsultDelete(consultId.ToString());
            return RedirectToAction("ConsultList", new {
                productId = productId,
                pageIndex = 1
            });
        }
        [Authorize(), HttpPost]
        public ActionResult ConsultEdit(ConsultViewModel cvm) {

            #region 检查数据合法性

            MessageHelper mh = new MessageHelper("consult");
            mh.AddBody(2);
            if (cvm.Consult.ConsultId > 0) {
                ConsultEntity ce = _consult.GetConsultById(cvm.Consult.ConsultId);
                if (ce.Uid != this._user.Uid) {
                    mh.AddMessage(4);
                }
                if (ce.IsAudit) {
                    mh.AddMessage(5);
                }
            }
            if (string.IsNullOrEmpty(cvm.Consult.Content)) {
                mh.AddMessage(3);
            }
            if (!mh.IsValid) {
                return this.MessageResult(mh.CreateMessage());
            }

            #endregion

            cvm.Consult.ProductId = cvm.Product.ProductId;
            cvm.Consult.Uid = this._user.Uid;
            cvm.Consult.Content = Htmls.EncodeHtml(cvm.Consult.Content);
            cvm.Consult.AddDate = DateTime.Now;
            cvm.Consult.ReplyDate = DateTime.Now;

            _consult.ConsultUpdate(cvm.Consult);

            return RedirectToAction("ConsultList", new {
                productId = cvm.Product.ProductId,
                pageIndex = 1
            });
        }

        #region AJAX

        [HttpPost]
        public ActionResult AjaxList(int productId = 0, string key = "") {
            ConsultParameters cp = new ConsultParameters() {
                ProductId = productId,
                PageIndex = 1,
                PageSize = 5,
                Uid = this._user.Uid,
                Key = key
            };
            List<ConsultEntity> consultList = _consult.GetConsultList(cp);

            return View(new ConsultViewModel() {
                ConsultList = consultList ?? new List<ConsultEntity>(),
                Product = new ProductEntity() { ProductId = productId },
                RowsCount = cp.RowsCount
            });
        }

        [HttpPost]
        public ActionResult AjaxSearch(int productId = 0, string key = "") {
            ConsultParameters cp = new ConsultParameters() {
                ProductId = productId,
                PageIndex = 1,
                PageSize = int.MaxValue,
                Uid = this._user.Uid,
                Key = key
            };
            List<ConsultEntity> consultList = _consult.GetConsultList(cp);

            return View(new ConsultViewModel() {
                ConsultList = consultList ?? new List<ConsultEntity>(),
                Product = new ProductEntity() { ProductId = productId },
                RowsCount = cp.RowsCount
            });
        }

        #endregion

        #region Private Methods

        private void AddSiteMapPath(ProductEntity productView) {
            // 当前分类
            ClassifyEntity currentClass = _classify.GetClassifyById(productView.ClassId);
            // sitemappath
            List<ClassifyEntity> pathList =
                _classify.GetClassifyByModuleKeyAndPath(_moduleKey,
                string.Format("{0}-{1}", currentClass.Path, currentClass.ClassifyId));
            if (pathList != null) {
                List<int> cPathList = new List<int>() { 0 };
                foreach (ClassifyEntity ce in pathList) {
                    cPathList.Add(ce.ClassifyId);
                    ProductParam ppPath = new ProductParam() {
                        Classify = cPathList
                    };
                    this.SiteMapPathAdd(ce.Title.Trim(), Url.Action("ProductList", "Product", new {
                        productParams = ppPath.ToString()
                    }));
                }
            }
        }

        #endregion
    }
}
